#!/bin/bash

function firefox_prepare() {
	if [ ! -d $HOME/.mozilla/firefox/*testing ]
	then
		echo "Preparing firefox profile"
		
		firefox --display=:$DISPLAY.0 -CreateProfile testing &
		sleep 10
		PROFILE=`ls -d $HOME/.mozilla/firefox/*testing`
		firefox_stop
	
		DUMMY=/etc/ssl/fedimbo.belgium.be/server.crt
	
		echo "Adding cert to profile $PROFILE"
		certutil -A -n "Fedimbo Wildcard" -t "P" -d $PROFILE -i $DUMMY
	fi
}

function X_start() {
	echo "Starting headless X"
	Xvfb :$DISPLAY -screen 0 1024x768x24 -ac -c -s 0 > /var/log/Xvfb.log 2>&1 &
	sleep 10
}

function firefox_start() {
	echo "Starting firefox"
	firefox --display=:$DISPLAY.0 -width 1024 -height 768 -P testing > /var/log/firefox.log &
	sleep 10
}

function record_start() {
	OUTDIR=/vagrant/output/screenshots
	if [ ! -d $OUTDIR ]
	then
		mkdir -p $OUTDIR
	fi
	
	echo "Starting ffmpeg"
	STAMP=`date +%Y%m%d%H%m`
	OUTFILE=$OUTDIR/movie-$STAMP.avi
	ffmpeg -f x11grab -an -y -r 20 -s 1024x768 -i :$DISPLAY.0 $OUTFILE -v warning > /var/log/ffmpeg.log 2>&1 &
}

function site_all() {
	for sitename in `ls /var/www/$PLATFORM/sites`
	do
		if [ $sitename != "all" ] && [ $sitename != "default" ]
		then
			/vagrant/sitescripts/site_shot.sh $sitename
		fi
		sleep 3
	done
}

function firefox_stop() {
	echo "Stopping firefox"
	pkill firefox
	pkill -9 firefox
}

function record_stop() {
	echo "Stopping ffmpeg"
	pkill ffmpeg
	pkill -9 ffmpeg
}

function X_stop() {
	echo "Stopping X"
	pkill Xvfb
	pkill -9 Xvfb
}


if [ $# -eq 1 ]
then
	PLATFORM=$1
	DISPLAY=9
	
	X_start
	record_start
	firefox_prepare
	firefox_start
	
	site_all
	
	firefox_stop
	record_stop
	X_stop
else
	echo "Usage: site_shot_all.sh <platform_name>"
	exit -1
fi